package com.shenhaofeng.app.log;

import android.os.Looper;

import com.shenhaofeng.app.device.DeviceInfo;


/**
 * Created by Administrator on 2016/10/12.
 */
public class GlobalErrorInitializer {


    private static GlobalErrorHandler globalErrorHandler;


    /**
     * 初始化处理器
     */
    public static void init(GlobalErrorHandler errorHandler) {
        checkThread();
        globalErrorHandler = errorHandler;
        Thread.UncaughtExceptionHandler uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandlerImpl(globalErrorHandler, uncaughtExceptionHandler));
        DeviceInfo.getSupported32BitABIS();
    }


    /**
     * 检查线程
     */
    private static void checkThread() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new IllegalStateException(
                    "Must be called from the main thread. Was: " + Thread.currentThread());
        }
    }


    static class UncaughtExceptionHandlerImpl implements Thread.UncaughtExceptionHandler {

        private GlobalErrorHandler mGlobalErrorHandler;

        private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;


        public UncaughtExceptionHandlerImpl(GlobalErrorHandler mGlobalErrorHandler, Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
            this.mGlobalErrorHandler = mGlobalErrorHandler;
            this.uncaughtExceptionHandler = uncaughtExceptionHandler;
        }


        @Override
        public void uncaughtException(Thread t, Throwable e) {
            mGlobalErrorHandler.uncaughtException(uncaughtExceptionHandler, t, e);
        }
    }


}
